<template>
  <v-card>
    <v-toolbar class="elevation-0">
      <v-btn color="primary" v-show="authorize.add" @click="addUser">新增用户</v-btn>
      <v-spacer/>
      <v-flex xs3>
        <v-text-field
          append-icon="search"
          label="搜索"
          single-line
          hide-details
          v-model="filter.search"
        />
      </v-flex>
    </v-toolbar>
    <v-divider/>
    <v-data-table
      :headers="headers"
      :items="userList"
      :pagination.sync="pagination"
      :total-items="total"
      :loading="loading"
      class="elevation-1"
      v-show="authorize.page"
    >
      <template slot="items" slot-scope="props">
        <td class="text-xs-center">{{ props.item.id }}</td>
        <td class="text-xs-center">{{ props.item.username }}</td>
        <td class="text-xs-center">{{props.item.phone}}</td>
        <td class="text-xs-center">{{props.item.name}}</td>
        <td class="text-xs-center">
          <img v-if="props.item.headImg" :src="props.item.headImg" width="40" height="40">
          <span v-else>无</span>
        </td>
        <td class="text-xs-center">{{ props.item.birthDate }}</td>
        <td class="text-xs-center">{{formartSex(props.item.sex)}}</td>
        <td class="text-xs-center">{{ props.item.isLocked?"是":"否" }}</td>
        <td class="justify-center layout px-0">
          <v-btn v-show="authorize.delete" icon v-if="props.item.isDelete" @click="deleteUser(props.item.id,props.item.isDelete)">恢复</v-btn>
          <v-btn v-show="authorize.delete" icon v-else @click="deleteUser(props.item.id,props.item.isDelete)">删除</v-btn>
          <v-btn v-show="authorize.locked" icon v-if="props.item.isLocked" @click="unlockUser(props.item.id,props.item.isLocked)">解锁</v-btn>
          <v-btn v-show="authorize.locked" icon v-else @click="lockedUser(props.item)">锁定</v-btn>
          <v-btn v-show="authorize.reset" @click="resetUserPwd(props.item.id)">重置密码</v-btn>
          <v-btn v-show="authorize.role" @click="setUserRole(props.item)">分配角色</v-btn>
        </td>
      </template>
    </v-data-table>

    <v-dialog v-model="show" max-width="700px" persistent scrollable>
          <v-card>
              <!--对话框的标题-->
                <v-toolbar dense dark color="primary">
                <v-toolbar-title>{{isEdit ? '修改' : '新增'}}用户</v-toolbar-title>
                <v-spacer/>
                <!--关闭窗口的按钮-->
                <v-btn icon @click="closeWindow"><v-icon>close</v-icon></v-btn>
              </v-toolbar>
              <v-card-text class="px-3" style="height: 400px">
                  <v-form v-model="valid" ref="basic">
                    <v-layout row>
                      <v-flex xs5>
                        <v-text-field v-model="oldUser.username"  label="用户名：" />
                      </v-flex>
                      <v-spacer/>
                      <v-flex xs5>
                        <v-text-field v-model="oldUser.phone"  label="手机号：" />
                      </v-flex>
                    </v-layout>
                    <v-layout row>
                      <v-flex xs5>
                        <v-text-field v-model="oldUser.name"  label="真实姓名：" />
                      </v-flex>
                      <v-spacer/>
                      <v-flex xs5>
                         <v-text-field v-model="oldUser.password"  label="密码：" />
                      </v-flex>
                    </v-layout>
                    <v-select
                      v-model="oldUser.roles"
                      :items="roleList"
                      :menu-props="{ maxHeight: '400' }"
                      label="角色分配（可多选）"
                      item-text="text"
                      item-value="value"
                      multiple
                    ></v-select>
                   </v-form>
              </v-card-text>
              <v-card-actions>
                  <v-spacer/>
                  <v-btn color="blue darken-1" flat @click.native="show=false">取消</v-btn>
                  <v-btn color="blue darken-1" flat @click.native="save">保存</v-btn>
              </v-card-actions>
          </v-card>
       </v-dialog>

       <!-- 锁定弹框 -->
       <v-dialog v-model="lockedShow" max-width="350px" persistent scrollable>
           <v-card>
               <!--对话框的标题-->
                 <v-toolbar dense dark color="primary">
                 <v-toolbar-title>锁定用户</v-toolbar-title>
                 <v-spacer/>
                 <!--关闭窗口的按钮-->
                 <v-btn icon @click="lockedShow=false"><v-icon>close</v-icon></v-btn>
               </v-toolbar>
               <v-card-text class="xs10 mx-auto" style="height: 150px">
                     <v-text-field v-model="lockedData.lockedDay" label="锁定天数：" />
               </v-card-text>
               <v-card-actions>
                   <v-spacer/>
                   <v-btn color="blue darken-1" flat @click.native="lockedShow=false">取消</v-btn>
                   <v-btn color="blue darken-1" flat @click.native="lockedSave">保存</v-btn>
               </v-card-actions>
           </v-card>
       </v-dialog>

       <!-- 分配角色弹框 -->
        <v-dialog v-model="userRoleShow" max-width="350px" persistent scrollable>
            <v-card>
                <!--对话框的标题-->
                  <v-toolbar dense dark color="primary">
                  <v-toolbar-title>分配用户角色</v-toolbar-title>
                  <v-spacer/>
                  <!--关闭窗口的按钮-->
                  <v-btn icon @click="userRoleShow=false"><v-icon>close</v-icon></v-btn>
                </v-toolbar>
                <v-card-text class="xs10 mx-auto" style="height: 200px">
                      <v-select
                        v-model="userRoleData.roles"
                        :items="roleList"
                        :menu-props="{ maxHeight: '400' }"
                        label="角色分配（可多选）"
                        item-text="text"
                        item-value="value"
                        multiple
                      ></v-select>
                </v-card-text>
                <v-card-actions>
                    <v-spacer/>
                    <v-btn color="blue darken-1" flat @click.native="userRoleShow=false">取消</v-btn>
                    <v-btn color="blue darken-1" flat @click.native="userRoleSave">保存</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
  </v-card>
</template>

<script>

  import {Message} from 'element-ui';

  export default {
    name: "member",
    data() {
      return {
        filter: {
          search: '', // 搜索过滤字段
        },
        total: 0, // 总条数
        userList: [], // 当前页品牌数据
        loading: true, // 是否在加载中
        pagination: {}, // 分页信息
        headers: [
          {text: 'id',align: 'center', sortable: false, value: 'id'},
          {text: '用户名', align: 'center', sortable: false, value: 'username'},
          {text: '手机号', align: 'center', sortable: false, value: 'phone'},
          {text: '真实姓名', align: 'center', sortable: false, value: 'name'},
          {text: '头像', align: 'center', value: 'headImg', sortable: false},
          {text: '出生日期', align: 'center', value: 'birthDate', sortable: false},
          {text: '性别', align: 'center', value: 'sex', sortable: false},
          {text: '是否锁定', align: 'center', value: 'isLocked', sortable: false},
          {text: '操作', align: 'center', sortable: false}
        ],
        show: false,// 控制用户新增对话框的显示
        lockedShow:false, //控制锁定弹框显示
        lockedData:{id:null,lockedDay:null,isLocked:null},
        userRoleShow:false, //控制分配角色按钮弹框显示
        userRoleData:{roles:[],id:null},
        isEdit: false, // 是否是编辑
        valid:false,
        roleList:[],
        oldUser:{
          username:"",
          phone:"",
          name:"",
          password:"",
          roles:[]
        },
        authorize:{page:false,add:false,delete:false,locked:false,reset:false,role:false}
      }
    },
    created(){
      this.$http({
        method: 'GET',
        url: '/user/author/query/other/auth?url='+this.$route.path,
        headers: {"x-authorize-token":this.$storeGet("L_TOKEN")},
      }).then((resp) => {
        if(resp.data.code == 1){
          resp.data.data.forEach(m => {
            if(m.url == '/user/user/page' && m.method == "POST"){
              this.authorize.page=true;
            }
            if(m.url == "/user/user" && m.method == "POST"){
              this.authorize.add=true;
            }
            if(m.url == "/user/locked" && m.method == "PUT"){
              this.authorize.locked=true;
            }
            if(m.url == "/user/user" && m.method == "DELETE"){
              this.authorize.delete=true;
            }
            if(m.url == "/user/reset" && m.method == "PUT"){
              this.authorize.reset=true;
            }
            if(m.url == "/user/update/role" && m.method == "PUT"){
              this.authorize.role=true;
            }
          })
        }else{
          this.$message.error(resp.data.message);
        }
      }).catch(() => {
        this.$message.error("服务器异常");
      });
    },
    mounted() { // 渲染后执行
      // 查询数据
      this.getDataFromServer();
      this.$http.get('/user/role/all',{headers: {"x-authorize-token":this.$storeGet("L_TOKEN")}}).then( resp => {
        if(resp.data.code == 1){
          let roleJson = [];
          if(resp.data.data.length > 0){
            resp.data.data.forEach((item) => {
              if(item.isDelete == 0){
                roleJson.push({value: item.id, text: item.roleCode});
              }
            });
          }
          this.roleList=roleJson;
        }else{
          this.$message.error(resp.data.message);
        }
      }).catch(() => {
        this.$message.error("服务器异常");
      });
    },
    watch: {
      pagination: { // 监视pagination属性的变化
        deep: true, // deep为true，会监视pagination的属性及属性中的对象属性变化
        handler() {
          // 变化后的回调函数，这里我们再次调用getDataFromServer即可
          this.getDataFromServer();
        }
      },
      filter: {// 监视搜索字段
        handler() {
          this.getDataFromServer();
        },
        deep: true
      }
    },
    methods: {
      getDataFromServer() { // 从服务的加载数的方法。
        // 发起请求
        this.$http({
          method: 'post',
          url: '/user/user/page',
          data:{
            key: this.filter.search, // 搜索条件
            saleable: this.filter.saleable === 0 ? null : this.filter.saleable, // 上下架
            page: this.pagination.page,// 当前页
            rows: this.pagination.rowsPerPage// 每页大小
          },
          headers: {"x-authorize-token":this.$storeGet("L_TOKEN")}
        }).then( resp => {
          if(resp.data.code == 1){
            this.userList = resp.data.data.items;
            this.total = resp.data.data.total;
            // 完成赋值后，把加载状态赋值为false
            this.loading = false;
          }else{
            this.$message.error(resp.data.message);
          }
        }).catch(() => {
          this.$message.error("服务器异常");
        });
      },
      addUser() {
        this.show = true;
        // 重置表单
        this.$refs.basic.reset();
      },
      save(){
        this.$http({
            method: 'post',
            url: '/user/user',
            data: this.oldUser,
        }).then((resp) => {
            if(resp.data.code == 1){
              this.show = false;
              this.$message.success("保存成功");
              this.getDataFromServer();
            }else{
              this.$message.error(resp.data.message);
            }
        }).catch(() => {
          this.$message.error("服务器异常");
        });
      },
      deleteUser(id,isDelete){
        this.$http({
            method: 'delete',
            url: '/user/user',
            data: {id:id,isDelete:isDelete},
            headers: {"x-authorize-token":this.$storeGet("L_TOKEN")}
        }).then((resp) => {
            if(resp.data.code == 1){
              this.$message.success(isDelete?"恢复成功":"删除成功");
              this.getDataFromServer();
            }else{
              this.$message.error(resp.data.message);
            }
        }).catch(() => {
          this.$message.error("服务器异常");
        });
      },
      resetUserPwd(id){
        this.$http({
            method: 'put',
            url: '/user/reset',
            data: {id:id},
            headers: {"x-authorize-token":this.$storeGet("L_TOKEN")}
        }).then((resp) => {
            if(resp.data.code == 1){
              this.$message.success("重置密码成功！");
              this.getDataFromServer();
            }else{
              this.$message.error(resp.data.message);
            }
        }).catch(() => {
          this.$message.error("服务器异常");
        });
      },
      closeWindow(){
        // 关闭窗口
        this.show = false;
      },
      setUserRole(user){
        this.$http({
            method: 'get',
            url: '/user/author/query/role/'+user.id,
            headers: {"x-authorize-token":this.$storeGet("L_TOKEN")}
        }).then((resp) => {
            if(resp.data.code == 1){
              this.userRoleShow=true;
              this.userRoleData.id=user.id;
              this.userRoleData.roles=[];
              resp.data.data.forEach((item) => {
                this.userRoleData.roles.push(item.id);
              });
            }else{
              this.$message.error(resp.data.message);
            }
        }).catch(() => {
          this.$message.error("服务器异常");
        });
      },
      userRoleSave(){
        this.$http({
            method: 'put',
            url: '/user/update/role',
            data: this.userRoleData,
            headers: {"x-authorize-token":this.$storeGet("L_TOKEN")}
        }).then((resp) => {
            if(resp.data.code == 1){
              this.userRoleShow=false;
              let userinfo = this.$storeGet("L_USERINFO");
              let id = this.userRoleData.id;
              Message({
                showClose: true,
                message: "设置用户角色成功！",
                type: 'success',
                duration:1500,
                onClose:function () {
                  if(id == userinfo.id){
                    location.href="/";
                  }
                }
              });
            }else{
              this.$message.error(resp.data.message);
            }
        }).catch(() => {
          this.$message.error("服务器异常");
        });
      },
      lockedUser(user){
        this.lockedShow = true;
        this.lockedData.id=user.id;
        this.lockedData.isLocked=user.isLocked;
        this.lockedData.lockedDay=null;
      },
      unlockUser(id,isLocked){
        this.lockedData.id=id;
        this.lockedData.isLocked=isLocked;
        this.lockedSave();
      },
      lockedSave(){
        this.$http({
            method: 'put',
            url: '/user/locked',
            data: this.lockedData,
            headers: {"x-authorize-token":this.$storeGet("L_TOKEN")}
        }).then((resp) => {
            if(resp.data.code == 1){
              this.lockedShow = false;
              this.$message.success(this.lockedData.isLocked?"解锁成功！":"锁定成功！");
              this.getDataFromServer();
            }else{
              this.$message.error(resp.data.message);
            }
        }).catch(() => {
          this.$message.error("服务器异常");
        });
      },
      formartSex(sex){
        if(sex == 0){
          return "保密";
        }else if(sex == 1){
          return "男";
        }else{
          return "女";
        }
      }
    }
  }
</script>

<style scoped>

</style>
